import scrapy

from scrapy_dangdang_095.items import ScrapyDangdang095Item


class DangSpider(scrapy.Spider):
    name = "dang"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["http://category.dangdang.com/cp01.01.02.00.00.00.html"]
    page = 1
    base_url = 'http://category.dangdang.com/pg'

    def parse(self, response):
        # src = //ul[@id="component_59"]/li//img/@data-original
        # name = //ul[@id="component_59"]/li//img/@alt
        # price = //ul[@id="component_59"]/li//p[@class="price"]/span[1]/text()
        # 所有的seletor的对象，都可以再次调用xpath方法
        li_list = response.xpath('//ul[@id="component_59"]/li')
        for li in li_list:
            # 列表的第一个数据的图片，跟其他的图片不一样
            src = li.xpath('.//img/@data-original').extract_first()
            if src:
                src = src
            else:
                src = li.xpath('.//img/@src').extract_first()
            name = li.xpath('.//img/@alt').extract_first()
            price = li.xpath('.//p[@class="price"]/span[1]/text()').extract_first()
            book = ScrapyDangdang095Item(src=src, name=name, price=price)

            # 获取一个book，就将book交给pipelines
            yield book
        # pass

        if self.page < 10:
            self.page = self.page + 1
            url = self.base_url + str(self.page) + '-cp01.01.02.00.00.00.html'

            # scrapy.Request就是scrapy的get请求 URL是请求地址， callback是要执行的函数（不用加参数）
            yield scrapy.Request(url=url, callback=self.parse)
